import React, { useState, useEffect } from 'react';
import { Radio } from 'antd';
import EditTable from './EditTable';

// 办公用品交接
const OfficeDepotCountersign = ({ value = [], onChange, config }) => {
    const [dataSource, setDataSource] = useState(value);
    const [ruleStatus, setRuleStatus] = useState(null);

    React.useEffect(() => {
        const { options } = config;
        setRuleStatus(options?.disabled);
    }, [config]);

    useEffect(() => {
        if (onChange) {
            onChange(dataSource);
        }
    }, [JSON.stringify(dataSource)]);

    useEffect(() => {
        if (value.length > 0) {
            const arr = value.map(item => {
                const obj = item;
                if (!item.isValidatorPass) {
                    obj.isValidatorPass = false;
                }
                return obj;
            });
            setDataSource(arr);
        }
    }, [JSON.stringify(value)]);

    const handleRowSave = row => {
        const newData = dataSource;
        const index = newData.findIndex(item => row.key === item.key);
        const item = newData[index];
        newData.splice(index, 1, {
            ...item,
            ...row,
            isValidatorPass: true
        });
        setDataSource([...newData]);
    };

    const columns = [
        {
            title: '交接事项',
            dataIndex: 'officesType',
            width: '30%'
        },
        {
            title: '详情说明',
            dataIndex: 'officesDetail',
            width: '30%'
        },
        {
            title: '交接方式',
            dataIndex: 'receiveType'
        },
        {
            title: '处理情况',
            dataIndex: 'receiveStatus',
            render: (text, record) => (
                <>
                    <Radio.Group
                        defaultValue={record.receiveStatus}
                        onChange={e => handleRowSave({ ...record, receiveStatus: e.target.value })}
                    >
                        <Radio value={1} disabled={ruleStatus}>
                            是
                        </Radio>
                        <Radio value={2} disabled={ruleStatus}>
                            否
                        </Radio>
                        <Radio value={3} disabled={ruleStatus}>
                            无
                        </Radio>
                    </Radio.Group>
                </>
            )
        }
    ];

    return <EditTable dataSource={dataSource} columns={columns} handleRowSave={handleRowSave} rowKey="key" />;
};

export default React.forwardRef(OfficeDepotCountersign);
